import uuid
from rest_framework import viewsets
from rest_framework.decorators import action
from system.models import Menu
from system.serializers import MenuSerializer
from libs.simple_responses import api_success


class MenuViewSet(viewsets.ModelViewSet):
    queryset = Menu.objects.all().order_by('-id')
    serializer_class = MenuSerializer
    ordering_fields = ('id',)

    def list(self, request, *args, **kwargs):
        items = []
        permissions = request.user.get_permissions()

        queryset = self.get_queryset().filter(enable=True).order_by('orderNo')
        instances = MenuSerializer(queryset, many=True).data
        id_map = {}
        accessable_instances = []
        for instance in instances:
            if instance['permissions'] and not bool(set(permissions) & set(instance['permissions'])):
                continue
            instance['name'] = uuid.uuid4()
            instance['meta']['orderNo'] = instance.pop('orderNo', None)
            instance['meta']['icon'] = instance.pop('icon', None)
            instance['meta']['title'] = instance.pop('title', None)
            instance['meta']['hideMenu'] = instance.pop('hideMenu', False)
            id_map[instance['id']] = instance
            instance['children'] = []
            accessable_instances.append(instance)

        for instance in accessable_instances:
            parent = instance.get('parent')
            if parent and parent in id_map:
                id_map[parent]['children'].append(instance)
            else:
                items.append(instance)
        return api_success(data=items)

    @action(methods=['get'], detail=False, url_path='manage-list')
    def list_for_manage(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset()).order_by('orderNo')
        instances = MenuSerializer(queryset, many=True).data

        id_map = {}
        for instance in instances:
            id_map[instance['id']] = instance
            instance['children'] = []

        items = []
        for instance in instances:
            parent = instance.get('parent')
            if parent:
                id_map[parent]['children'].append(instance)
            else:
                items.append(instance)

        data = {
            'total': len(items),
            'items': items
        }
        return api_success(data=data)
